package rainy.file.synchronization.server.commond.exec;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import rainy.file.synchronization.config.RainyRunTime;
import rainy.file.synchronization.server.MonitorServerHandler;
import rainy.file.synchronization.server.commond.Command;
import rainy.file.synchronization.server.commond.CommondExecutor;

public class FileTransCommandExecutor implements CommondExecutor<String> {
	private String folder = RainyRunTime.getPropDefine("rainy.master.target.folder");

	public String supportedCommond() {
		return RainyRunTime.COMMOND_FILE;
	}

	@Override
	public void executeCommand(Command<String> command) {
		String msg = command.getFullContent();
		/**
		 * 处理原来的文件传输的逻辑暂时不处理
		 */
		if (msg.indexOf("#") > 0) {
			String[] strs = msg.split("#");
			File file = new File(folder, strs[0]);
			System.out.println("[FileTransCommandExecutor | sever] 收到 " + command.getRemoteAddress() + " | " + file);
			if (!file.exists()) {
				synchronized (MonitorServerHandler.class) {
					try {
						createFile(file);
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			byte[] b = new org.apache.commons.codec.binary.Base64().decode(strs[1]);
			try (FileOutputStream fos = new FileOutputStream(file)) {
				fos.write(b);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	/**
	 * 首先创建所有的parent目录，然后创建文件
	 * 
	 * @param file
	 * @throws IOException
	 */
	private void createFile(File file) throws IOException {
		if (!file.getParentFile().exists()) {
			file.getParentFile().mkdirs();
		}
		if (!file.exists()) {
			file.createNewFile();
		}
	}

}
